package com.cqs.learning.spring.cloud.producer.web;

import com.cqs.learning.spring.cloud.producer.service.impl.DegradeServiceImpl;
import com.cqs.learning.spring.cloud.producer.service.RedisSentinelRulesService;
import io.lettuce.core.TransactionResult;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * 限流降级演示类
 *
 * @author lixw
 * @date created in 21:25 2020/4/5
 */
@RestController
public class DegradeController {
    @Autowired
    private DegradeServiceImpl degradeService;

    @Autowired
    private RedisSentinelRulesService sentinelRulesService;

    /**
     * 限流测试
     *
     * @return
     */
    @GetMapping("/flow")
    public String flow() {
        return String.valueOf(degradeService.flow());
    }

    /**
     * 熔断测试
     *
     * @param mill
     * @return
     */
    @RequestMapping("/degrade")
    public String degrade(@RequestParam(value = "sleep", defaultValue = "1000") int mill) {
        return String.valueOf(degradeService.errorReq(mill));
    }

    /**
     * @return
     * @throws IOException
     */
    @RequestMapping("/rules")
    public TransactionResult setRules(@Param("rules") String rules, @Param("type") Integer type) throws IOException {
        TransactionResult result = null;
        if (type == 0) {
            URL resource = Thread.currentThread().getContextClassLoader().getResource("config/flowRules.json");
            List<String> list = FileUtils.readLines(new File(resource.getFile()));
            rules = list.stream().reduce("", (s, s2) -> s += s2);
            result = sentinelRulesService.pushFlowRules(rules);
        } else if (type == 1) {
            URL resource = Thread.currentThread().getContextClassLoader().getResource("config/DegradeRule.json");
            List<String> list = FileUtils.readLines(new File(resource.getFile()));
            rules = list.stream().reduce("", (s, s2) -> s += s2);
            result = sentinelRulesService.pushDegradeRules(rules);
        }
        return result;
    }
}
